package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@Topic(TopicConfig.VMS_RESULT_TOPIC)
public class VmResultHandler implements MsgHandler {
    @Autowired
    OrderService orderService;
    @Override
    public void process(String jsonMsg) throws IOException {
        //1.Json转换对应的协议类
        VendoutResultContract contract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        //2.参数校验
        if (contract == null) {
            log.info("接收售货机终端协议类order中，传递的参数不能为空");
            throw new LogicException("接收售货机终端协议类，传递的参数不能为空");
        }
        VendoutData vendoutData = contract.getVendoutData();
        log.info("接收到售货机传递的出货消息,订单号:{}" + vendoutData.getOrderNo());
        //获取订单
        OrderEntity order = orderService.getByOrderNo(vendoutData.getOrderNo());
        //3.判断修改订单状态
        if (contract.isSuccess()) {//出货成功
                order.setStatus(VMSystem.ORDER_STATUS_VENDOUT_SUCCESS);//支付状态
            log.info("出货成功  订单号:{}",vendoutData.getOrderNo());
        }else {//出货失败退款
            order.setStatus(VMSystem.ORDER_STATUS_VENDOUT_FAIL);//支付状态
            order.setPayStatus(VMSystem.PAY_STATUS_REFUNDING);
            //TODO:退款
            log.info("出货失败,发起退款 订单号:{}",vendoutData.getOrderNo());
        }
        orderService.updateById(order);
    }
}
